package com.primaryedu.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.primaryedu.dialog.CustomDialog;
import com.primaryedu.utils.Logger;
import com.primaryedu.utils.StatusBarCompat;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.loading.ShapeLoadingDialog;

/**
 * Created by Administrator on 2018/9/12.
 */

public abstract class BaseAppCompatActivity extends AppCompatActivity {

    protected ProgressDialog loadDialog;
    protected Dialog dialog;
    private Handler handler = new Handler();
    protected RequestQueue requestQueue = null;

    InputMethodManager inputManager;
    LayoutInflater inflater;
    private CustomDialog.Builder ibuilder;
    private SVProgressHUD mSVProgressHUD;
    private Toast toast;
    private ShapeLoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        setContentView(BindLayout());

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        StatusBarCompat.compat(this, Color.BLACK);

        if (isNeedTranslucentStatus()) {

            setTranslucentStatus();

        }
        //初始化布局
        initView();

        //初始化数据
        init();
        initData();
    }

    private void init() {
        mSVProgressHUD = new SVProgressHUD(this);
        loadDialog = Utils.initRequestDialog(this);
        requestQueue = Volley.newRequestQueue(this);
        inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        dialog = Utils.initRequestDialog(this);
    }


    /*
     * 绑定一个布局id
     */
    @LayoutRes
    protected abstract int BindLayout();

    /**
     * 查找id,或者初始化toolbar的标题
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 设置是否需要沉浸式
     *
     * @return
     */
    public boolean isNeedTranslucentStatus() {
        return false;
    }

    /**
     * 设置沉浸式
     */
    private void setTranslucentStatus() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        // 这个属性4.4算是全透明（有的机子是过渡形式的透明），5.0就是半透明了 我的模拟器、真机都是半透明，

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4 全透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 5.0 全透明实现
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);// calculateStatusColor(Color.WHITE, (int) alphaValue)

        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
        return super.onTouchEvent(event);
    }

   /* protected void showLoading(String content) {
        mSVProgressHUD.showWithStatus(content);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mSVProgressHUD.isShowing()) {
//                    Toast.makeText(BaseAppCompatActivity.this, "网络链接错误，请稍后再试!", Toast.LENGTH_SHORT).show();
                    mSVProgressHUD.dismiss();
                }
            }
        }, 6000);
    }

    protected void dismissLoading() {
        mSVProgressHUD.dismiss();
    }*/

    protected void errorLoading(String content) {
        mSVProgressHUD.showErrorWithStatus(content, SVProgressHUD.SVProgressHUDMaskType.GradientCancel);
    }

    protected void showDialog() {
        if (null != dialog) {
            dialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (dialog.isShowing()) {
                        Toast.makeText(BaseAppCompatActivity.this, "网络链接错误，请稍后再试!", Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }
            }, 60000);
        }
    }

    protected void showDialog(final String str) {
        if (null != dialog) {
            dialog.show();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (dialog.isShowing()) {
                        Toast.makeText(BaseAppCompatActivity.this, str, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                    }
                }
            }, 60000);
        }
    }

    protected void closeDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
    }

    /**
     * [绑定控件]
     *
     * @param resId
     * @return
     */
    protected <T extends View> T $(@IdRes int resId) {
        return (T) super.findViewById(resId);
    }


    /**
     * 消息提示框
     *
     * @param message 提示消息文本
     */

    protected void showToast(String message) {
//        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        try {
            if (toast != null) {
                toast.setText(message);
            } else {
                toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
            }
            toast.show();
        } catch (Exception e) {
            // 解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
            toast.show();
            Looper.loop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void onPause() {
        super.onPause();
    }

    public void showhintDialog(String title, String content) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton("确定", null)
                .show();
    }


    /**
     * 获取当前Activity类名
     *
     * @return 类名字符串
     */
    protected String getName() {
        return getClass().getSimpleName();
    }
    /**
     * 获取目标类的类名
     *
     * @param targetClass 需要获取名称的类
     * @return 类名字符串
     */
    protected String getName(Class<?> targetClass) {
        return targetClass.getSimpleName();
    }


    /**
     * 跳转页面
     *
     * @param targetActivity 所跳转的目的Activity类
     *
     * if中的判断条件就是验证当前Activity是正确，如果正确，则执行startActivity(intent)；
     * 不正确，项目中只是不执行对应的跳转操作，但是会打印出哪个类无法获取的Error。
     */
    public void jumpTo(Class<?> targetActivity) {
        Intent intent = new Intent(this, targetActivity);
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivity(intent);
        } else {
            Logger.withTag(getName()).log("activity not found for " + getName(targetActivity));
        }
    }

    /**
     * 跳转页面
     *
     * @param targetActivity 所跳转的目的Activity类
     * @param bundle         跳转所携带的信息
     */
    public void jumpbundleTo(Class<?> targetActivity, Bundle bundle) {
        Intent intent = new Intent(this, targetActivity);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivity(intent);
        } else {
            Logger.withTag(getName()).log("activity not found for " + getName(targetActivity));
        }
    }

    /**
     * 跳转页面
     *
     * @param targetActivity 所跳转的Activity类
     * @param requestCode    请求码
     */
    public void jumpTo(Class<?> targetActivity, int requestCode) {
        Intent intent = new Intent(this, targetActivity);
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(intent, requestCode);
        } else {
            Logger.withTag(getName()).log("activity not found for " + getName(targetActivity));
        }
    }

    /**
     * 跳转页面
     *
     * @param targetActivity 所跳转的Activity类
     * @param bundle         跳转所携带的信息
     * @param requestCode    请求码
     */
    public void jumpTo(Class<?> targetActivity, int requestCode, Bundle bundle) {
        Intent intent = new Intent(this, targetActivity);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            startActivityForResult(intent, requestCode);
        } else {
            Logger.withTag(getName()).log("activity not found for " + getName(targetActivity));
        }
    }

    protected void showLoading(String content) {
        showLoadingDialog(content);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                loadingDialog.dismiss();
            }
        }, 6000);
    }

    /**
     * 显示Loading窗口
     *
     * @param content 提示内容, 如果为null 则显示默认文字: "正在加载中..."
     */
    public ShapeLoadingDialog showLoadingDialog(@Nullable String content) {
        return showLoadingDialog(content, null);
    }

    /**
     * 显示Loading窗口
     *
     * @param content        提示内容, 如果为null 则显示默认文字: "正在加载中..."
     * @param cancelListener 按返回键取消Loading的监听
     */
    public ShapeLoadingDialog showLoadingDialog(@Nullable String content, DialogInterface.OnCancelListener cancelListener) {
        loadingDialog = new ShapeLoadingDialog(this);
        loadingDialog.setLoadingText(content == null ? "加载中..." : content);
        if (cancelListener != null) {
            loadingDialog.setOnCancelListener(cancelListener);
        } else {
            loadingDialog.setCancelable(false);
        }
        loadingDialog.show();
        return loadingDialog;
    }
    /**
     * Loading窗口消失
     *
     */
    protected void dismissLoading() {
        loadingDialog.dismiss();
    }
}
